<?php
/**
 * "Job" Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class Job extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{jobs}}':
     * @var integer $id
     * @var string $title
     * @var integer $published_date
     * @var string $closing_date
     * @var string $work_place
     * @var integer $quantity
     * @var integer $education_level
     * @var integer $sex
     * @var string $summary
     * @var string $summary_formatted
     * @var integer $clicks_count
     * @var integer $status
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

     public $clicks_count = 0;

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{jobs}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('title, published_date, closing_date, work_place, summary', 'required'),
            array('node_id, published_date, closing_date, quantity, education_level, sex, clicks_count, status, order_pos, created, updated', 'numerical', 'integerOnly' => true),
            array('title', 'length', 'max' => 200),
            array('work_place', 'length', 'max' => 20),
            array('closing_date', 'checkClosingDate')
        );
    }

    public function checkClosingDate() {
        if ($this->closing_date < $this->published_date) {
            $this->addError('closing_date', Yii::t('job', 'closing date must greater than published date'));
        }
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            'node' => array(self::BELONGS_TO, 'Node', 'node_id')
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'title' => Yii::t('job', 'title'),
            'published_date' => Yii::t('job', 'published_date'),
            'closing_date' => Yii::t('job', 'closing_date'),
            'work_place' => Yii::t('job', 'work_place'),
            'quantity' => Yii::t('job', 'quantity'),
            'education_level' => Yii::t('job', 'education_level'),
            'sex' => Yii::t('options', 'sex'),
            'summary' => Yii::t('job', 'summary'),
            'clicks_count' => Yii::t('common', 'clicks_count'),
            'status' => Yii::t('options', 'status'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxFormat() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/jobs/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#yuandot{$this->id}",
            ),
            array('id' => "yuandot{$this->id}")
        );
    }

    // "updated" field formatted
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    const EDUCATION_LEVEL_0 = 0;
    const EDUCATION_LEVEL_1 = 1;
    const EDUCATION_LEVEL_2 = 2;
    const EDUCATION_LEVEL_3 = 3;
    const EDUCATION_LEVEL_4 = 4;
    const EDUCATION_LEVEL_5 = 5;
    const EDUCATION_LEVEL_6 = 6;
    const EDUCATION_LEVEL_7 = 7;
    const EDUCATION_LEVEL_8 = 8;
    public function getEducationLevelOptions() {
        return array(
            self::EDUCATION_LEVEL_0 => Yii::t('job', 'education_level_0'),
            self::EDUCATION_LEVEL_1 => Yii::t('job', 'education_level_1'),
            self::EDUCATION_LEVEL_2 => Yii::t('job', 'education_level_2'),
            self::EDUCATION_LEVEL_3 => Yii::t('job', 'education_level_3'),
            self::EDUCATION_LEVEL_4 => Yii::t('job', 'education_level_4'),
            self::EDUCATION_LEVEL_5 => Yii::t('job', 'education_level_5'),
            self::EDUCATION_LEVEL_6 => Yii::t('job', 'education_level_6'),
            self::EDUCATION_LEVEL_7 => Yii::t('job', 'education_level_7'),
            self::EDUCATION_LEVEL_8 => Yii::t('job', 'education_level_8'),
        );
    }

    public function getEducationLevelTextFormat() {
        $options = $this->educationLevelOptions;
        return (isset($options[$this->education_level]))
            ? $options[$this->education_level] : 'unknown';
    }

    public function getSexTextFormat() {
        $options = $this->sexOptions;
        return (isset($options[$this->sex]))
            ? $options[$this->sex] : 'unknown';
    }

    public function getQuantityTextFormat() {
        return ($this->quantity) ? $this->quantity : Yii::t('job', 'unlimit');
    }

    const SEX_NONE = 0;
    const SEX_MALE = 1;
    const SEX_FEMALE = 2;
    public function getSexOptions() {
        return array(
            self::SEX_NONE => Yii::t('job', 'sex_none'),
            self::SEX_MALE => Yii::t('job', 'sex_male'),
            self::SEX_FEMALE => Yii::t('job', 'sex_female'),
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    protected function beforeValidate() {
        parent::beforeValidate();
        $this->published_date = strtotime($this->published_date);
        $this->closing_date = strtotime($this->closing_date);

        $parser = new CMarkdownParser();
        $this->summary_formatted = $parser->safeTransform($this->summary);
        return true;
    }
    
    protected function afterFind() {
        $this->published_date = date('Y-m-d', $this->published_date);
        $this->closing_date = date('Y-m-d', $this->closing_date);
    }

    private function findBase($type = 'recent', $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        $criteria->addCondition('closing_date >= ' . time());
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        switch ($type) {
            case 'recent':
                $criteria->order = 'created DESC';
                break;
            case 'hot':
                $criteria->order = 'clicks_count DESC';
                break;
            default:
                $criteria->order = 'created DESC';
                break;
        }
        $criteria->limit = $limit;

        return self::model()->findAll($criteria);
    }

    public function findRecent($node = null, $limit = 12) {
        return $this->findBase('recent', $node, $limit);
    }

    public function findHot($node = null, $limit = 12) {
        return $this->findBase('hot', $node, $limit);
    }

}